<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/27 0027
 * Time: 上午 11:09
 */

namespace App\Tools;

use Illuminate\Support\Facades\Storage;

class Files
{
    private $size; //文件大小

    private $name; //文件名称

    private $extension; //文件扩展名

    private $file; //操作的文件对象

    private $realPath; //临时文件 apache tmp下的文件

    private $filesystems; //上传文件路径配置 配置文件在config/filesystems目录下

    private $resultRoot; //存放目录的

    public function __set($name, $value)
    {
        // TODO: Implement __set() method.
        $this->$name = $value;
    }

    public function __get($name)
    {
        // TODO: Implement __get() method.
        return $this->$name;
    }

    public function __construct($file)
    {

        $this->file = $file;
        $this->extension = $this->file->getClientOriginalExtension();
        $this->size = $this->file->getSize();
        $this->name = $this->file->getClientOriginalName();
        $this->realPath = $this->file->getRealPath();
        $this->filesystems = 'storage';
    }

    /*上传文件*/
    private function move()
    {
        $resultRoot = config("filesystems.disks.{$this->filesystems}.url");

        if ($this->file->isValid()) {
            //文件上传
            $filename = date('Y-m-d-H-i-s') . '-' . uniqid() . '.' . $this->extension;

            $bool = Storage::disk($this->filesystems)->put($filename, file_get_contents($this->realPath));

            $resultRoot = $resultRoot . $filename;

            return $bool ? $resultRoot : false;
        }
    }

    /*只能上传图片*/
    public function imgUploader($maxSize = 5 * 1024 * 1024)
    {
        $extension = ['gif', 'jpg', 'jpeg', 'png'];
        if (!in_array($this->extension, $extension)) {
            return false;
        }
        if ($this->size > $maxSize) {
            return false;
        }
        return $this->move();
    }

    //复制文件
    public function copy($oldPath, $nawPath)
    {
        return Storage::copy($oldPath, $nawPath);
    }

}